//
//  LNHGoodsDetailViewController.m
//  LNH
//
//  Created by cruise on 2018/2/1.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "LNHGoodsDetailViewController.h"

#import "LNHGoodsDetailViewModel.h"

#import "LNHCyclePagerView.h"
#import "LNHCyclePagerViewCell.h"

#import "LNHGoodsDetailInfoView.h"
#import "LNHGoodsDetailSelectView.h"
#import "LNHGoodsDetailBottomView.h"
#import "LNHGoodsDetailTitleView.h"

#import "LNHGoodsInfoPopView.h"
#import "LNHSelectGoodsParametersPopView.h"

#import <WebKit/WebKit.h>

#import "LNHConfirmOrderViewController.h"
#import "CAShopCartViewController.h"
#import <WMPlayer/WMPlayer.h>

@interface LNHGoodsDetailViewController () <LNHCyclePagerViewDataSource, LNHCyclePagerViewDelegate, WKUIDelegate, WKNavigationDelegate, LNHGoodsDetailSelectViewDelegate, LNHGoodsDetailBottomViewDelegate>

@property (nonatomic, strong) LNHGoodsDetailViewModel *viewModel;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) LNHCyclePagerView *pagerView;
@property (nonatomic, strong) UILabel *pageNumLabel;

@property (nonatomic, strong) LNHGoodsDetailInfoView *infoView;
@property (nonatomic, strong) LNHGoodsDetailSelectView *selectView;

@property (nonatomic, strong) LNHGoodsDetailTitleView *titleView;
@property (nonatomic, strong) LNHGoodsDetailBottomView *bottomView;

@property (nonatomic, strong) LNHGoodsInfoPopView *infoPopView;
@property (nonatomic, strong) LNHSelectGoodsParametersPopView *selectPopView;

@property (nonatomic, strong) WKWebView *wkWebView;

@property (nonatomic) CGFloat wbContentHeight;

@property (nonatomic, strong) WMPlayer *wmPlayer;

@end

@implementation LNHGoodsDetailViewController

- (void)lm_initialDefaultsForController
{
    [self setViewModel:[[LNHGoodsDetailViewModel alloc] initWithParams:self.params]];
}

- (void)lm_configNavigationForController
{
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}



-(void)lm_bindViewModelForController
{
    @weakify(self);
    
    [[RACObserve(self.viewModel, goodsImageList) filter:^BOOL(NSArray *list) {
        return list.count > 0;
    }] subscribeNext:^(NSArray *list) {
        @strongify(self);
            
        [self.pagerView reloadData];
            
//            NSLog(@"list:%@", list);
    }];
    
    [self.viewModel.fetchGoodsDetailDataCommand execute:nil];
    
    // 监听取商品详细信号是否在执行
    [[self.viewModel.fetchGoodsDetailDataCommand.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
        @strongify(self);
        
        if (x.boolValue) {
            [MBProgressHUD showActivityIndicatorWithTip:@"加载中..."];
        }else {
            [MBProgressHUD hideHUD];
        }
    }];
    
    [[RACObserve(self.viewModel, infoDict) filter:^BOOL(id  _Nullable value) {
        return value != nil;
    }] subscribeNext:^(NSDictionary *dict) {
        @strongify(self);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.wkWebView loadHTMLString:dict[kPropertyDataKeyGoodsDetailHtmlString] baseURL:nil];
        });
        
        
    }];
}

- (void)lm_createViewForController
{
    
    self.title = @"产品详情";
    
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.contentView];
    
    [self.contentView addSubview:self.pagerView];
    
    [self.pagerView addSubview:self.pageNumLabel];
    
    [self.contentView addSubview:self.infoView];
    [self.contentView addSubview:self.selectView];
    [self.contentView addSubview:self.titleView];
    [self.contentView addSubview:self.wkWebView];
    
    [self.view addSubview:self.bottomView];
    
    [self.view setNeedsUpdateConstraints];
}

#pragma mark - Layout

- (void)updateViewConstraints
{
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(isIPhoneX ? 78 : 44);
    }];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.mas_equalTo(SCREEN_WIDTH);
//        make.height.greaterThanOrEqualTo(@0.f);
    }];
    
    [self.pagerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(5);
        make.left.right.equalTo(self.contentView);
        make.height.mas_equalTo(220);
    }];
    
    [self.pageNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.pagerView.mas_bottom).offset(-15);
        make.right.equalTo(self.pagerView.mas_right).offset(-10);
        make.width.mas_equalTo(45);
        make.height.mas_equalTo(22);
    }];
    
    [self.infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pagerView.mas_bottom);
        make.left.right.equalTo(self.contentView);
        make.height.mas_equalTo(100);
    }];
    
    [self.selectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.infoView.mas_bottom).offset(10);
        make.left.right.equalTo(self.contentView);
        make.height.mas_equalTo(80);
    }];
    
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.selectView.mas_bottom).offset(10);
        make.left.right.equalTo(self.contentView);
        make.height.mas_equalTo(47);
    }];
    
    [self.wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleView.mas_bottom);
        make.left.right.equalTo(self.contentView);
        make.height.greaterThanOrEqualTo(@0.f);
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.wkWebView.mas_bottom);
    }];
    
    [super updateViewConstraints];
}

#pragma mark - Getter

-(UIScrollView *) scrollView {
    if (!_scrollView) {
        _scrollView = [UIScrollView new];
        [_scrollView setBackgroundColor:RGBCOLOR(240, 240, 240)];
    }
    return _scrollView;
}

-(UIView *) contentView {
    if (!_contentView) {
        _contentView = [UIView new];
        [_contentView setUserInteractionEnabled:YES];
        [_contentView setBackgroundColor:RGBCOLOR(240, 240, 240)];
    }
    return _contentView;
}

-(LNHCyclePagerView *) pagerView {
    if (!_pagerView) {
        _pagerView = [[LNHCyclePagerView alloc]init];
        _pagerView.isInfiniteLoop = NO;
//        _pagerView.autoScrollInterval = 3.0;
        _pagerView.dataSource = self;
        _pagerView.delegate = self;
        
        [_pagerView registerClass:[LNHCyclePagerViewCell class] forCellWithReuseIdentifier:GCN(LNHCyclePagerViewCell)];
    }
    return _pagerView;
}

-(UILabel *) pageNumLabel {
    if (!_pageNumLabel) {
        _pageNumLabel = [UILabel new];
        [_pageNumLabel setBackgroundColor:RGBACOLOR(0, 0, 0, 0.3)];
        [_pageNumLabel.layer setCornerRadius:11];
        [_pageNumLabel.layer setMasksToBounds:YES];
        [_pageNumLabel setTextColor:[UIColor whiteColor]];
        [_pageNumLabel setTextAlignment:NSTextAlignmentCenter];
        [_pageNumLabel setFont:[UIFont systemFontOfSize:12]];
        [_pageNumLabel setHidden:YES];
    }
    return _pageNumLabel;
}

-(LNHGoodsDetailInfoView *) infoView {
    if (!_infoView) {
        _infoView = [LNHGoodsDetailInfoView new];
        [_infoView bindViewModel:self.viewModel withParams:nil];
    }
    return _infoView;
}

-(LNHGoodsDetailSelectView *) selectView {
    if (!_selectView) {
        _selectView = [LNHGoodsDetailSelectView new];
        [_selectView setDelegate:self];
    }
    return _selectView;
}

-(LNHGoodsDetailTitleView *) titleView {
    if (!_titleView) {
        _titleView = [LNHGoodsDetailTitleView new];
    }
    return _titleView;
}

-(WKWebView *) wkWebView {
    if (!_wkWebView) {
        
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        
        [wkUController addUserScript:wkUScript];
        
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        
        wkWebConfig.userContentController = wkUController;
        
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        _wkWebView.scrollView.scrollEnabled = NO;
    }
    return _wkWebView;
}

-(LNHGoodsDetailBottomView *) bottomView {
    if (!_bottomView) {
        _bottomView = [LNHGoodsDetailBottomView new];
        [_bottomView setDelegate:self];
        [_bottomView bindViewModel:self.viewModel withParams:nil];
    }
    return _bottomView;
}

-(LNHGoodsInfoPopView *) infoPopView{
    if (!_infoPopView) {
        _infoPopView = [LNHGoodsInfoPopView new];
        [_infoPopView bindViewModel:self.viewModel withParams:nil];
    }
    return _infoPopView;
}

-(LNHSelectGoodsParametersPopView *) selectPopView{
    if (!_selectPopView) {
        _selectPopView = [LNHSelectGoodsParametersPopView new];
        [_selectPopView bindViewModel:self.viewModel withParams:nil];
    }
    return _selectPopView;
}



#pragma mark - TYCyclePagerViewDataSource

- (NSInteger)numberOfItemsInPagerView:(LNHCyclePagerView *)pageView {
    return self.viewModel.goodsImageList.count;
}

- (UICollectionViewCell *)pagerView:(LNHCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index {
    LNHCyclePagerViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:GCN(LNHCyclePagerViewCell) forIndex:index];
    
    NSDictionary *dict = self.viewModel.goodsImageList[index];
    NSLog(@"dict==%@",dict);
    if (self.viewModel.hasVideo) {
        if (index == 0) {
            cell.isVideo = YES;
            [cell.wmPlayer setURLString:dict[kPropertyDataKeyGoodsDetailBannerUrl]];
            self.wmPlayer = (WMPlayer *) cell.wmPlayer;
        } else {
            cell.isVideo = NO;
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:dict[kPropertyDataKeyGoodsDetailBannerUrl]]];
        }
    } else {
        cell.isVideo = NO;
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:dict[kPropertyDataKeyGoodsDetailBannerUrl]]];
    }
    

    return cell;
}

- (LNHCyclePagerViewLayout *)layoutForPagerView:(LNHCyclePagerView *)pageView {
    LNHCyclePagerViewLayout *layout = [[LNHCyclePagerViewLayout alloc]init];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, 220);
    layout.itemSpacing = 0;
    //layout.minimumAlpha = 0.3;
    layout.itemHorizontalCenter = YES;
    return layout;
}

- (void)pagerView:(LNHCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (self.viewModel.hasVideo) {
            if (toIndex == 0) {
                [self.pageNumLabel setHidden:YES];
            } else {
                [self.pageNumLabel setHidden:NO];
                [self.wmPlayer pause];
            }
            
            [self.pageNumLabel setText:[NSString stringWithFormat:@"%ld/%ld", toIndex, self.viewModel.goodsImageList.count-1]];
        } else {
            [self.pageNumLabel setHidden:NO];
            [self.pageNumLabel setText:[NSString stringWithFormat:@"%ld/%ld", toIndex+1, self.viewModel.goodsImageList.count]];
        }
        
    });
    
//    NSLog(@"%ld ->  %ld",fromIndex,toIndex);
}

#pragma mark - WKNavigationDelegate

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"加载完成");
    //这个方法也可以计算出webView滚动视图滚动的高度
    [webView evaluateJavaScript:@"document.body.scrollWidth"completionHandler:^(id _Nullable result,NSError * _Nullable error){
        
        CGFloat ratio =  CGRectGetWidth(self.wkWebView.frame) /[result floatValue];
        
//        NSLog(@"scrollWidth高度：%.2f",[result floatValue]);
//        NSLog(@"ratio：%.2f",ratio);
        
        [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){
//            NSLog(@"scrollHeight高度：%.2f",[result floatValue]);
//            NSLog(@"scrollHeight计算高度：%.2f",[result floatValue]*ratio);
            CGFloat newHeight = [result floatValue]*ratio;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.wkWebView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(newHeight);
                }];
                
            });
            
            
        }];
        
    }];
}

#pragma mark - LNHGoodsDetailSelectViewDelegate

-(void) popSelectSizeView {
    [self.selectPopView showView];
}

-(void) popGoodsInfoView {
    [self.infoPopView showView];
}

//

#pragma mark - LNHGoodsDetailBottomViewDelegate

-(void) goHomeAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void) buyAction{
    
    NSString *number = @"1";
    NSString *skuStr = @"";
    NSString *levelId = self.viewModel.levelId == nil ? @"":self.viewModel.levelId;
    if (self.viewModel.skuAttrList.count > 0) {
//        NSString *skuId = [self.viewModel.selectSkuList componentsJoinedByString:@"-"];
//        NSLog(@"%@", self.viewModel.skuDict[skuId][@"id"]);
//        skuStr = self.viewModel.skuDict[skuId][@"id"];
        [self.selectPopView showView];
    } else {
        NSString *router = [JLRoutes lm_generateURLWithPattern:LMNavPushRoute parameters:@[NSStringFromClass(LNHConfirmOrderViewController.class)] extraParameters:@{@"goodsId":self.viewModel.infoDict[@"kPropertyListDataKeyID"],@"sku":skuStr,@"number":number,@"level":levelId,@"inviteCode":self.params[@"inviteCode"] == nil ? @"":self.params[@"inviteCode"]}];
        [[RACScheduler mainThreadScheduler] schedule:^{
            
            [[UIApplication sharedApplication] openURL:JLRGenRouteURL(LMDefaultRouteSchema, router) options:nil completionHandler:nil];
            
        }];
    }
}

-(void) goToShopcarAction{
    CAShopCartViewController *shopCartVC = [CAShopCartViewController new];
    shopCartVC.isHome = NO;
    [self.navigationController pushViewController:shopCartVC animated:YES];
}

-(void) addShopcarAction{
    [self.selectPopView showView];
}


@end
